<template>
	<view class="change-table">
		<view class="header">
			<text class="title">选择新餐桌</text>
			<text class="subtitle">当前餐桌：{{ currentBoardName }}</text>
		</view>
		
		<!-- 餐桌列表 -->
		<scroll-view scroll-y class="tables-list" :style="{ height: scrollHeight + 'px' }">
			<view v-if="freeBoards.length === 0" class="empty-tip">
				<text>暂无可用餐桌</text>
			</view>
			<view 
				v-for="board in freeBoards" 
				:key="board.boardId"
				class="table-item"
				@click="handleSelectTable(board)"
			>
				<view class="table-info">
					<text class="table-name">{{ board.boardName }}</text>
					<view class="table-details">
						<text class="seat-count">{{ board.seat }}人桌</text>
						<text class="table-type">{{ board.boardType }}</text>
					</view>
				</view>
				<text class="select-icon">✓</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { boardApi } from '../../utils/api'

const orderId = ref('')
const boardId = ref('')
const freeBoards = ref([])
const scrollHeight = ref(0)
const currentBoardName = ref('')

// 获取当前餐桌信息
const fetchCurrentBoard = async () => {
	try {
		console.log('开始获取当前餐桌信息，boardId:', orderId.value)
		// 确保boardId是数字
		const boardId = parseInt(orderId.value)
		console.log('转换后的boardId:', boardId)
		
		const result = await boardApi.getBoardById(boardId)
		console.log('获取到的当前餐桌数据:', result)
		
		if (result.code === 200) {
			uni.$emit('tableChanged', {
				orderId: orderId.value,
				newBoard: result.data
			})
		} else {
			throw new Error(result.message || '获取餐桌信息失败')
		}
	} catch (error) {
		console.error('获取当前餐桌信息失败:', error)
		uni.showToast({
			title: '获取餐桌信息失败',
			icon: 'none'
		})
	}
}

// 获取空闲餐桌列表
const fetchFreeBoards = async () => {
	try {
		console.log('开始获取餐桌列表')
		const result = await boardApi.getBoards([9, 10])
		console.log('获取到的餐桌数据:', result)
		
		if (result.code === 200 && Array.isArray(result.data)) {
			// 筛选出空闲状态的餐桌，并排除当前餐桌
			freeBoards.value = result.data.filter(board => 
				board.boardStatus === 'UNINHABITED' && 
				board.boardId !== orderId.value
			)
			console.log('筛选后的空闲餐桌:', freeBoards.value)
			
			if (freeBoards.value.length === 0) {
				uni.showToast({
					title: '暂无可用餐桌',
					icon: 'none'
				})
			}
		} else {
			throw new Error(result.message || '获取餐桌列表失败')
		}
	} catch (error) {
		console.error('获取餐桌列表出错:', error)
		uni.showToast({
			title: error.message || '获取餐桌列表失败',
			icon: 'none'
		})
	}
}

// 选择餐桌
const handleSelectTable = (board) => {
	uni.showModal({
		title: '确认换桌',
		content: `确定要将订单从 ${currentBoardName.value} 换到 ${board.boardName} 吗？`,
		success: async (res) => {
			if (res.confirm) {
				try {
					uni.showLoading({
						title: '换桌中...'
					})
					
					const result = await boardApi.changeBoard(board.boardId, orderId.value)
					console.log('换桌结果:', result)
					
					if (result.code === 200) {
						uni.showToast({
							title: '换桌成功',
							icon: 'success'
						})
						// 返回首页并刷新数据
						uni.reLaunch({
							url: '/src/pages/order/index'
						})
					} else {
						throw new Error(result.message || '换桌失败')
					}
				} catch (error) {
					console.error('换桌失败:', error)
					uni.showToast({
						title: error.message || '换桌失败',
						icon: 'none'
					})
				} finally {
					uni.hideLoading()
				}
			}
		}
	})
}

// 计算滚动区域高度
const calculateScrollHeight = () => {
	const systemInfo = uni.getSystemInfoSync()
	const headerHeight = 180 // 头部区域高度（rpx转px）
	scrollHeight.value = systemInfo.windowHeight - uni.upx2px(headerHeight)
}

// 页面加载时获取数据
onLoad((options) => {
	console.log('页面加载参数:', options)
	if (options.boardName && options.boardId && options.orderId) {
		currentBoardName.value = options.boardName
		boardId.value = options.boardId
		orderId.value = options.orderId
		calculateScrollHeight()
		// 延迟一下再获取数据，确保页面已经渲染
		setTimeout(() => {
			fetchFreeBoards()
		}, 100)
	} else {
		uni.showToast({
			title: '参数不完整',
			icon: 'none'
		})
	}
})

onMounted(() => {
	calculateScrollHeight()
})
</script>

<style lang="scss" scoped>
.change-table {
	min-height: 100vh;
	background: #f5f5f5;
	display: flex;
	flex-direction: column;
	
	.header {
		background: #ffffff;
		padding: 30rpx;
		border-bottom: 1rpx solid #eee;
		
		.title {
			font-size: 36rpx;
			font-weight: 600;
			color: #333;
			display: block;
			margin-bottom: 10rpx;
		}
		
		.subtitle {
			font-size: 26rpx;
			color: #666;
		}
	}
	
	.test-content {
		padding: 20rpx;
		background: #fff;
		margin: 20rpx;
		border-radius: 12rpx;
		text-align: center;
		color: #666;
		font-size: 28rpx;
	}
	
	.tables-list {
		flex: 1;
		padding: 20rpx;
		
		.empty-tip {
			text-align: center;
			padding: 40rpx;
			color: #999;
			font-size: 28rpx;
		}
		
		.table-item {
			background: #ffffff;
			border-radius: 12rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			
			&:active {
				opacity: 0.8;
			}
			
			.table-info {
				flex: 1;
				
				.table-name {
					font-size: 32rpx;
					font-weight: 600;
					color: #333;
					margin-bottom: 10rpx;
					display: block;
				}
				
				.table-details {
					display: flex;
					gap: 20rpx;
					
					.seat-count, .table-type {
						font-size: 26rpx;
						color: #666;
						background: #f5f5f5;
						padding: 4rpx 16rpx;
						border-radius: 20rpx;
					}
				}
			}
			
			.select-icon {
				font-size: 40rpx;
				color: #c70209;
				opacity: 0;
				transition: opacity 0.3s;
				
				&.active {
					opacity: 1;
				}
			}
		}
	}
}
</style> 